<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import dayjs from 'dayjs'
import type { SelectProps } from 'ant-design-vue'
import DataLeavesCountAnalyze from '@/components/analyze/DataLeavesCountAnalyze.vue'
import DataLeavesSizeAnalyze from '@/components/analyze/DataLeavesSizeAnalyze.vue'
import VChart from 'vue-echarts'
import 'echarts'
import DataLeavesColorDetailAnalyze from '@/components/analyze/DataLeavesColorDetailAnalyze.vue'
import DataHeightAnalyze from '@/components/analyze/DataHeightAnalyze.vue'
import { getCropData, getFieldList } from '@/api/cropGrowthIndicatorsController.ts'

const searchParams = reactive({
  id: '',
  startEditTime: '',
  endEditTime: '',
})

const loading = ref<boolean>(false)
const showing = ref<boolean>(false)
const leavesCountDate = ref<any>([]) // 叶片数量对应日期
const leavesCountData = ref<any[]>([]) // 叶片数量数据
const leavesSizeDate = ref<any>([]) // 叶片大小对应日期
const leavesSizeData = ref<any[]>([]) // 叶片大小数据
const leavesColorDate = ref<any>([]) // 叶片颜色对应日期
const darkGreenData = ref<any[]>([]) // 暗绿色数据
const yellowData = ref<any[]>([]) // 黄色数据
const witheredData = ref<any[]>([]) // 枯萎数据
const whiteData = ref<any[]>([]) // 白化数据
const heightDate = ref<any>([]) // 高度对应日期
const heightData = ref<any[]>([]) // 高度数据

const dateRange = ref<[]>([])

/**
 * 日期范围更改时触发
 * @param dates
 * @param dateStrings
 */
const onRangeChange = (dates: any[], dateStrings: string[]) => {
  if (dates.length < 2) {
    searchParams.startEditTime = ''
    searchParams.endEditTime = ''
  } else {
    searchParams.startEditTime = dates[0].toDate()
    searchParams.endEditTime = dates[1].toDate()
  }
}

const rangePresets = ref([
  { label: '过去 7 天', value: [dayjs().add(-7, 'd'), dayjs()] },
  { label: '过去 14 天', value: [dayjs().add(-14, 'd'), dayjs()] },
])

const fieldOptions = ref<SelectProps['options']>([])

const options = computed(() => {
  return {
    graphic: {
      elements: [
        {
          type: 'group',
          left: 'center',
          top: 'center',
          children: new Array(7).fill(0).map((val, i) => ({
            type: 'rect',
            x: i * 20,
            shape: {
              x: 0,
              y: -40,
              width: 10,
              height: 80,
            },
            style: {
              fill: '#5470c6',
            },
            keyframeAnimation: {
              duration: 1000,
              delay: i * 200,
              loop: true,
              keyframes: [
                {
                  percent: 0.5,
                  scaleY: 0.3,
                  easing: 'cubicIn',
                },
                {
                  percent: 1,
                  scaleY: 1,
                  easing: 'cubicOut',
                },
              ],
            },
          })),
        },
      ],
    },
  }
})

const doSearch = async () => {
  loading.value = true
  showing.value = false
  const res = await getCropData({
    id: parseInt(searchParams.id),
    startEditTime: searchParams.startEditTime,
    endEditTime: searchParams.endEditTime,
  })
  // 叶片数量
  leavesCountData.value = res.data.data?.leavesCountData?.leafTotalCounts
  leavesCountDate.value = res.data.data?.leavesCountData?.recordTimes
  // 叶片大小
  leavesSizeData.value = res.data.data?.leavesSizeData?.leafAvgSizes
  leavesSizeDate.value = res.data.data?.leavesSizeData?.recordTimes
  // 叶片颜色
  darkGreenData.value = res.data.data?.leavesColorDetailData?.leafDarkGreenRatios
  yellowData.value = res.data.data?.leavesColorDetailData?.leafYellowingRatios
  witheredData.value = res.data.data?.leavesColorDetailData?.leafWitheredRatios
  whiteData.value = res.data.data?.leavesColorDetailData?.leafAlbinoRatios
  leavesColorDate.value = res.data.data?.leavesColorDetailData?.recordTimes
  // 高度
  heightData.value = res.data.data?.plantHeightData?.plantHeights
  heightDate.value = res.data.data?.plantHeightData?.recordTimes
  loading.value = false
  showing.value = true
}

// 清理
const doClear = () => {
  // 取消所有对象的值
  Object.keys(searchParams).forEach((key) => {
    searchParams[key] = undefined
  })
  dateRange.value = []
}

const getFieldIds = async () => {
  const res = await getFieldList()
  const fieldIdList = res.data.data
  if (fieldIdList === undefined || fieldIdList.length === 0) {
    return
  }
  fieldOptions.value = fieldIdList.map((item: any) => ({ value: item, label: item }))
}

onMounted(() => {
  getFieldIds()
})
</script>

<template>
  <div class="center-container">
    <!-- 搜索表单 -->
    <a-form layout="inline" :model="searchParams" @finish="doSearch">
      <a-form-item label="田块号" name="id">
        <a-select
          v-model:value="searchParams.id"
          style="min-width: 180px"
          :options="fieldOptions"
          placeholder="请输入田块号"
        />
      </a-form-item>
      <a-form-item label="日期" name="">
        <a-range-picker
          style="width: 400px"
          v-model:value="dateRange"
          :placeholder="['编辑开始日期', '编辑结束时间']"
          format="YYYY/MM/DD HH:mm:ss"
          :presets="rangePresets"
          @change="onRangeChange"
        />
      </a-form-item>
      <a-form-item>
        <a-space>
          <a-button type="primary" html-type="submit" style="width: 96px">搜索</a-button>
          <a-button html-type="reset" @click="doClear">重置</a-button>
        </a-space>
      </a-form-item>
    </a-form>
  </div>
  <div v-if="loading">
    <v-chart :option="options" style="height: 400px; max-width: 100%" />
  </div>
  <div v-if="showing">
    <DataLeavesCountAnalyze :date="leavesCountDate" :leaves-count="leavesCountData" />
    <DataLeavesSizeAnalyze :record-date="leavesSizeDate" :leaf-avg-size="leavesSizeData" />
    <DataLeavesColorDetailAnalyze
      :time-axis="leavesColorDate"
      :dark-green-data="darkGreenData"
      :yellow-data="yellowData"
      :withered-data="witheredData"
      :white-data="whiteData"
    />
    <DataHeightAnalyze :date="heightDate" :height-data="heightData" />
  </div>
</template>

<style scoped>
.center-container {
  display: flex;
  justify-content: center; /* 水平居中 */
  padding: 20px;
}

.picture-search-form .ant-form-item {
  margin-top: 16px;
}
</style>
